package com.autumn.security.session;

import com.autumn.runtime.session.IAutumnSession;
import com.autumn.runtime.session.claims.IdentityClaims;
import com.autumn.security.context.AutumnSecurityContextHolder;
import com.autumn.security.user.IAutumnUser;
import com.autumn.util.function.FunctionOneResult;

/**
 * 安全 AutumnSession 会话
 * 
 * @author 老码农
 *         <p>
 *         Description
 *         </p>
 * @date 2017-11-04 04:07:47
 */
public class SecurityAutumnSession implements IAutumnSession {

	/**
	 * 
	 */
	public SecurityAutumnSession() {

	}

	/**
	 * 
	 * @param fun
	 * @param defaultValue
	 * @return
	 */
	protected <TValue> TValue getAutumnUserValue(FunctionOneResult<IAutumnUser, TValue> fun, TValue defaultValue) {
		IAutumnUser user = AutumnSecurityContextHolder.getAutumnUser();
		if (user == null) {
			return defaultValue;
		}
		return fun.apply(user);
	}

	@Override
	public final Long getUserId() {
		return this.getAutumnUserValue(u -> {
			return u.getId();
		}, null);
	}

	@Override
	public final String getUserName() {
		IAutumnUser user = AutumnSecurityContextHolder.getAutumnUser();
		if (user != null) {
			return user.getUserName();
		}
		return null;
	}

	@Override
	public IdentityClaims getIdentityClaims() {
		return AutumnSecurityContextHolder.getIdentityClaims();
	}

	@Override
	public String getIdentityType() {
		IAutumnUser user = AutumnSecurityContextHolder.getAutumnUser();
		if (user != null) {
			return user.getIdentityType();
		}
		return null;
	}

}
